package com.apes.fn.pi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.crm.customerExpand.FnCustomerExpandRepository;
import com.apes.fn.server.productRequire.ProductRequire;
import com.apes.fn.server.productRequire.ProductRequireItem;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.account.repository.StockRepository;
import com.apes.scm.masterdata.car.repository.CarModelServiceLevelRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.finance.model.BankAccount;
import com.apes.scm.masterdata.finance.repository.AmtReceiptRepository;
import com.apes.scm.masterdata.finance.repository.BankAccountRepository;
import com.apes.scm.masterdata.frame.model.Channel;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.ChannelRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.DcDistributionRangeRepository;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wuq
 * @create 2019-12-19 15:31
 */
@Service("piService")
public class PiService extends DomainService {

    @Autowired
    private StockRepository stockRepository;
    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    public PartyRoleRepository partyRoleRepository;
    @Autowired
    private BankAccountRepository bankAccountRepository;
    @Autowired
    private PiManager piManager;
    @Autowired
    private ChannelRepository channelRepository;
    @Autowired
    private CarModelServiceLevelRepository carModelServiceLevelRepository;
    @Autowired
    private PiDao piDao;
    @Autowired
    private AmtReceiptRepository amtReceiptRepository;

    public List queryStock(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        long id = jsonObject.getLong("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<Map> stocks = stockRepository.findStocksByTs(date, id, PageRequest.of(0, maxNum));
        return stocks;
    }

    public List queryLocation(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        return locationRepository.findLocationByTs(date, id, PageRequest.of(0, maxNum));
    }

    public List queryEmployee(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        return employeeRepository.findByLikeName(id).stream().filter(Employee::isDriver).collect(Collectors.toList());
    }

    /**
     *  提过APP的保险供应商接口
     * @param request
     * @return
     */
    public List<Map<String, Object>> getAllSupplier(SimpleRequest request){
//        String value = request.get("key");
        String partyType = "Supplier";
        JSONObject jsonObject = request.getJO();
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");

        Date timestamp = new Date(jsonObject.getLong("timestamp"));
//        String id = jsonObject.getString("id"); //  最后更新ID
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数

        List<Map<String, Object>> partyList = partyRoleRepository.querySupplier(timestamp, PageRequest.of(0, maxNum));
        partyList.forEach(parts-> {
            parts.put("lastUpdatedStamp",DateToString((Date) parts.get("lastUpdatedStamp"),"yyyy-MM-dd HH:mm:ss.SSS"));
        });
        return partyList;
    }

    /**
     *  APP获取价格接口
     * @param request
     * @return
     */
    public JSONArray getPriceForApp(SimpleRequest request) throws RuntimeException{
        JSONObject jsonObject = request.getJO();
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");
        Date timestamp = new Date(jsonObject.getLong("timestamp"));  //时间戳
        String sPriceType = jsonObject.getString("priceType"); //需要获取的价格类型
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数

        String sConditionID = "", sDimFieldList = "", sPriceFieldList = "";

        if ("CGJG".equals(sPriceType)){ //采购价格文件
            sConditionID = "T03";
            sDimFieldList = "PRODUCT_ID,SUPPLIER_ID";
            sPriceFieldList = "P001,P004,P005";
        } else if ("DSJG".equals(sPriceType)){ //电商价格
            sConditionID = "T30";
            sDimFieldList = "PRODUCT_ID";
            sPriceFieldList = "Z002,S210";
        } else if ("SQDSJG".equals(sPriceType)){ //商圈电商价格
            sConditionID = "T30";
            sDimFieldList = "PRODUCT_ID,BUSINESS_CIRCLE_ID";
            sPriceFieldList = "Z002,S210";
        } else if ("FWDJJG".equals(sPriceType)){ //车型服务等级价格
            sConditionID = "T17";
            sDimFieldList = "PRODUCT_ID,CAR_SERVICE_LEVEL_ID";
            sPriceFieldList = "S008";
        } else if ("FWDJXS".equals(sPriceType)){ //车型服务等级系数
            sConditionID = "T18";
            sDimFieldList = "CLASSIFY_ID,CAR_SERVICE_LEVEL_ID";
            sPriceFieldList = "S110";
        } else {
            throw new RuntimeException("priceType 参数无效！");
        }
        String tableName = invoke("condition.qryConditionMidTabName",
                MapUtil.mapper("SYS_DIM_FIELD", sDimFieldList, "conditionId", sConditionID)).toString();
        String sDimId = tableName.substring(5,8);
        String sSql =
                "SELECT * FROM (" +
                "  SELECT * FROM (" +
                "    SELECT B.ID AS CLTZDH,A.ID AS NBDH, A.START_DATE,A.END_DATE,A.PRIORITY," +
                "           A.LAST_UPDATED_STAMP, STATE, " +
                "          " + sDimFieldList + "," + sPriceFieldList +
                "      FROM " + tableName + "_EXEC A, EXE_CONDITION_SUM B\n" +
                "     WHERE A.ID=B.B_ID AND B.CONDITION_ID='" + sConditionID + "' AND B.DIMENSION_ID='" + sDimId + "'" +
                "    UNION ALL" +
                "    SELECT C.ID AS CLTZDH,A.ID AS NBDH, A.START_DATE,A.END_DATE,A.PRIORITY," +
                "           A.LAST_UPDATED_STAMP, STATE, " +
                "          " + sDimFieldList + "," + sPriceFieldList +
                "      FROM " + tableName + " A, " + tableName + "_ITEM B, EXE_CONDITION_SUM C\n" +
                "     WHERE A.ID=B.ID AND A.ID=C.B_ID AND A.STOP_DATE IS NOT NULL" +
                "       AND C.CONDITION_ID='" + sConditionID + "' AND C.DIMENSION_ID='" + sDimId + "'" +
                "    UNION ALL" +
                "    SELECT B.ID AS CLTZDH,A.ID AS NBDH, A.START_DATE,A.END_DATE,A.PRIORITY," +
                "           A.LAST_UPDATED_STAMP, 'stop' STATE, " +
                "          " + sDimFieldList + "," + sPriceFieldList +
                "      FROM " + tableName + "_EXEC_STOP A, EXE_CONDITION_SUM B\n" +
                "     WHERE A.ID=B.B_ID AND A.STATE='exec' AND B.CONDITION_ID='" + sConditionID + "' AND B.DIMENSION_ID='" + sDimId + "'" +
                "  ) WHERE LAST_UPDATED_STAMP > :timeStamp ORDER BY LAST_UPDATED_STAMP" +
                ") WHERE ROWNUM<=:maxNum";
        JSONObject param = new JSONObject();
        param.put("timeStamp", timestamp);
        param.put("maxNum", maxNum);
        System.out.println(sSql);
        return piDao.querySql(sSql, param);
    }

    /**
     * 检查一批商品是否都存在采购价格文件，返回没有价格的商品编码
     * @param request
     * @return
     */
    public JSONArray checkPriceExists(SimpleRequest request){
        JSONObject getJO = request.getJO();
        String supplier = getJO.getString("supplier");
        String company = getJO.getString("company");
        String accessProvider = getJO.getString("accessProvider");
        JSONArray productIds = getJO.getJSONArray("productIds");
        String tableName1 = invoke("condition.qryConditionMidTabName",
                MapUtil.mapper("SYS_DIM_FIELD", "PRODUCT_ID,SUPPLIER_ID", "conditionId", "T03")).toString(); // SUPPLIER_ID
        String tableName2 = invoke("condition.qryConditionMidTabName",
                MapUtil.mapper("SYS_DIM_FIELD", "PRODUCT_ID,SUPPLIER_ID,OPERATOR_ID", "conditionId", "T04")).toString(); // OPERATOR_ID
        String tableName3 = invoke("condition.qryConditionMidTabName",
                MapUtil.mapper("SYS_DIM_FIELD", "PRODUCT_ID,SUPPLIER_ID,ACCESS_PROVIDER_ID", "conditionId", "T04")).toString(); // ACCESS_PROVIDER_ID
        String sProduct = "";
        JSONArray sNoPrice = new JSONArray();
        for (int i=0;i<productIds.size();i++){
            if (i==0){
                sProduct = productIds.get(i).toString();
            }else{
                sProduct = sProduct + "," + productIds.get(i);
            }
        }
        List<Map> operators = getBean(PartyRepository.class).findOperator(company);
        String operatorId = operators.isEmpty()?"":operators.get(0).get("OPERATOR_ID") + "";
        StringBuilder sSqls = new StringBuilder();
        String sSql1 = "SELECT PRODUCT_ID FROM "+tableName1+"_EXEC WHERE PRODUCT_ID IN ("+sProduct+") AND SUPPLIER_ID = '" + supplier + "' UNION ";
        String sSql2 = "SELECT PRODUCT_ID FROM "+tableName2+"_EXEC WHERE PRODUCT_ID IN ("+sProduct+") AND OPERATOR_ID = '" + operatorId + "' UNION ";
        String sSql3 = "SELECT PRODUCT_ID FROM "+tableName3+"_EXEC WHERE PRODUCT_ID IN ("+sProduct+") AND ACCESS_PROVIDER_ID = '" + accessProvider + "'";
        sSqls.append(sSql1);
        sSqls.append(sSql2);
        sSqls.append(sSql3);
        JSONArray arrSP = piDao.querySql(sSqls.toString());
        List<String> existsProductIds = arrSP.stream().map(arrSPObj -> {return ((JSONObject)arrSPObj).getString("PRODUCT_ID");}).collect(Collectors.toList());
        if (arrSP.size() == productIds.size()){
            return sNoPrice;
        }
        for (int i=0;i<productIds.size();i++){
            String obj = productIds.get(i).toString();
            if (!existsProductIds.contains(obj)) sNoPrice.add(obj);
        }
        return sNoPrice;
    }

    /**
     * 获取历史平台服务费
     * @param request
     * @return
     * @throws Exception
     */
    public Map<String, Object> getHistoryStrategy_FW01(SimpleRequest request) throws Exception{
        JSONObject jsonObject = request.getJO();
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("deptId")), "门店编码不能为空!!!");
        Date timestamp = new Date(jsonObject.getLong("timestamp"));  //时间戳
        String deptId = jsonObject.getString("deptId");
        String sSql = "SELECT A.ID, A.NAME, A.COMPANY_ID, C.OPERATION\n" +
                "  FROM MAS_DEPT A, MAS_PARTY_ROLE B, MAS_CORPORATE C\n" +
                " WHERE A.COMPANY_ID=B.ID AND B.PARTY_ID=C.PARTY_ID AND A.ID = :deptId";
        JSONArray arrDept = piDao.querySql(sSql, jsonObject);
        if ((arrDept == null)||(arrDept.size() == 0)){
            throw new RuntimeException("部门编码【"+deptId+"】不存在！");
        }
        Map<String, Object> strategyMap = new HashMap<>();
        strategyMap.put("COMPANY_ID", arrDept.getJSONObject(0).getString("COMPANY_ID"));
        strategyMap.put("OPERATION", arrDept.getJSONObject(0).getString("OPERATION"));
        strategyMap.put("SYS_RQ", timestamp);
        strategyMap.put("conditionId", "FW01");        //取平台服务费
        Object obj = this.invoke("condition.getCondition", strategyMap);
        double dT001 = 0.0;
        if (((com.apestech.framework.json.JSONObject) obj).get("T001") != null){
            dT001 = ((com.apestech.framework.json.JSONObject) obj).getDouble("T001");
        }
        strategyMap.put("T001", dT001);
        return strategyMap;
    }

    /**
     *  APP获取车型服务等级数据
     * @param request
     * @return
     */
    public List<Map> getCarModelServiceLevelForApp(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");

        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数

        List<Map> carModelServiceLevelList = carModelServiceLevelRepository.findCarModelServiceLevelsByTs(timestamp, id, PageRequest.of(0, maxNum));
        return carModelServiceLevelList;
    }

    /**
     *  APP获取商圈包含地区数据
     * @param request
     * @return
     */
    public JSONArray getBusinessCircleAreasForApp(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");

        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数

        String sSql = "SELECT * FROM ( " +
                " SELECT A.ID AS BUSINESS_CIRCLE_ID, A.NAME AS BUSINESS_CIRCLE_NAME," +
                "        B.AREA_ID, C.NAME AS AREA_NAME, TO_CHAR(A.LAST_UPDATED_STAMP,'yyyymmdd hh24:mi:ssxff3') AS LAST_UPDATED_STAMP\n" +
                "   FROM MAS_BUSINESS_CIRCLE A, MAS_BUSINESS_CIRCLE_AREA B, MAS_AREA C " +
                "  WHERE A.ID = B.BUSINESS_CIRCLE_ID AND B.AREA_ID = C.ID " +
                "    AND A.LAST_UPDATED_STAMP > :timeStamp ORDER BY A.LAST_UPDATED_STAMP" +
                ") WHERE ROWNUM<=:maxNum";
        JSONObject param = new JSONObject();
        param.put("timeStamp", timestamp);
        param.put("maxNum", maxNum);
        System.out.println(sSql);
        return piDao.querySql(sSql, param);
    }

    /**
     * String --> Date
     * @param date
     * @param dateFormat
     * @return
     */
    public String DateToString( Date date, String dateFormat){
        DateFormat format = new SimpleDateFormat(dateFormat);
        String dateString = format.format(date);
        return dateString;
    }

    /***
     * 功能：增量获取银行账户接口
     */
    public JSONArray getAllBankAccount(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        Assert.isTrue(!StringUtils.isEmpty(jsonObject.getString("timestamp")), "时间戳不能为空!!!");

        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数

        String sSql = "SELECT * FROM (\n" +
                "SELECT A.ID, A.NAME, A.BANK_ID, B.NAME AS BANK_NAME, A.BANK_BRANCH,\n" +
                "       A.ACCOUNT_ID, A.ACCOUNT_NAME, A.PAY_SIGN, A.RECEIPT_SIGN, A.COMPANY_ID,\n" +
                "       TO_CHAR(A.LAST_UPDATED_STAMP,'yyyymmdd hh24:mi:ssxff3') AS LAST_UPDATED_STAMP \n" +
                "  FROM MAS_BANK_ACCOUNT A, MAS_BANK B\n" +
                " WHERE A.BANK_ID = B.ID\n" +
                "   AND A.LAST_UPDATED_STAMP > :timeStamp\n" +
                "     ORDER BY A.LAST_UPDATED_STAMP\n" +
                "    ) WHERE ROWNUM<=:maxNum";
        JSONObject param = new JSONObject();
        param.put("timeStamp", timestamp);
        param.put("maxNum", maxNum);
        System.out.println(sSql);
        JSONArray array = piDao.querySql(sSql, param);
        return array;
    }

    /***
     * 功能：提供对外的银行账户接口
     * @param request
     * @return
     */
    public List findAllBankAccountForApp(SimpleRequest request) {
        JSONObject tempJson = request.getJO();
        List<BankAccount> bankAccounts = bankAccountRepository.findAll(
                JpaDsl.toCriteriaIgnoreNull(
                        "bank.id", "EQ", tempJson.get("bankId"),
                        "accountId", "EQ", tempJson.get("account_id"),
                        "receiptSign", "EQ", tempJson.getBoolean("receipt_sign"),
                        "paySign", "EQ", tempJson.getBoolean("pay_sign")
                )
        );
        return bankAccounts;
    }
	
	/**
     * 同步 partyRole 角色为 Customer、公司类型为corporate 的数据
     * @param simpleRequest
     * @return
     */
    public JSONObject queryCustomer(SimpleRequest simpleRequest) {
        String ts01 = JSONObject.parseObject(simpleRequest.getData().toString()).getString("TS01");
        JSONObject returnData = new JSONObject();
        returnData.put("item", partyRoleRepository.queryCustomer(ts01));
        return returnData;
    }
	
	@Listener(topic="event:piService.synTempoProduct")
    public JSONObject synTempoProduct(SimpleRequest simpleRequest) {

        // 生成老系统商品
        JSONObject synOldSpxxObj = piManager.synErp("mdmSpxxService.insertSynReturnNewFrame", simpleRequest.getJO());
        if (!synOldSpxxObj.getBooleanValue("success")) throw new RuntimeException(synOldSpxxObj.getString("msg"));

        // 生成新系统商品信息
        String spid = synOldSpxxObj.getString("obj");
        JSONObject resultObj = piManager.synErp("mdmSpxxService.insertNewProduct", MapUtil.mapper("SPID", spid));
        if (!resultObj.getBooleanValue("success")) throw new RuntimeException(resultObj.getString("msg"));

        return synOldSpxxObj;
    }

    public List queryChannel(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        return channelRepository.findChannelByTs(date, id, PageRequest.of(0, maxNum));
    }

    /**
     *  DC配送范围(APP)
     * @param request
     * @return
     */
    public List queryDcDistributionRange(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = null;
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数
        String id = jsonObject.getString("id");
        if (jsonObject.get("timestamp") == null || jsonObject.get("maxNum") == null) {
            throw new RuntimeException("传入参数时间和本次请求最大值参数确实，请检查！");
        }
        try {
            timestamp = new Date(jsonObject.getLong("timestamp"));
        } catch (Exception e) {
            throw new RuntimeException("传入时间戳格式错误");
        }
        List<Map> dcDistributionRanges = SpringManager.getBean(DcDistributionRangeRepository.class).queryDcDistributionByTs(timestamp, PageRequest.of(0, maxNum), id);
        return dcDistributionRanges;
    }

    /**
     *  创建要货单(APP)
     */
    public Object createAndApproveProductRequire(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        ProductRequire productRequire = new ProductRequire();
        //创建人
        productRequire.setCreator(request.get("creatorId").toString());
        //库存位置
        Location location = SpringManager.getBean(LocationRepository.class).findOne(request.get("locationId").toString());
        productRequire.setLocation(location);
        //公司
        productRequire.setCompany(location.getCompany());

        if(jsonObject.get("channelId") != null) {
            //渠道编码
            Channel channel = new Channel();
            channel.setId(jsonObject.getString("channelId"));
            productRequire.setChannel(channel);
        }
        //平台
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(request.get("deptId").toString());
        String id = Optional.ofNullable(dept)
                .map(Dept::getCompany)
                .map(PartyRole::getParty)
                .map(Party::getCorporate)
                .map(Corporate::getOperation)
                .map(Enumeration::getId).orElse(null);
        if ("001073".equals(id)) {
            productRequire.setPlatform(partyRoleRepository.findOne("1007"));
        } else
            productRequire.setPlatform(partyRoleRepository.findOne("1001"));
        //备注
        productRequire.setRemark(jsonObject.getString("remark"));
        List<FnCustomerExpand> carLicense = SpringManager.getBean(FnCustomerExpandRepository.class).findAllByCarLicense(jsonObject.getString("carLicense"));
        if (carLicense != null && carLicense.size() > 0) {
            productRequire.setCustomerExpand(carLicense.get(0));
        } else throw new RuntimeException("找不会员信息，请检查车牌");
        //拼明细
        JSONArray items = request.getJO().getJSONArray("items");
        List<ProductRequireItem> list = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            ProductRequireItem productRequireItem = new ProductRequireItem();
            productRequireItem.setProductRequire(productRequire);
            //公司
            productRequireItem.setCompany(location.getCompany());
            //商品
            Product product = SpringManager.getBean(ProductRepository.class).findOne(item.get("productId").toString());
            if (product == null) throw new RuntimeException("查询不到商品：ID【"+item.get("productId").toString()+"】");
            productRequireItem.setProduct(product);
            productRequireItem.setUom(product.getUom());
            //要货数量
            productRequireItem.setQtyRequire(Double.valueOf(item.get("qtyRequire").toString()));
            productRequireItem.setRemark(item.get("remark").toString());
            list.add(productRequireItem);
        }
        productRequire.setProductRequireItems(list);
        List<User> userInfo = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", productRequire.getCreator()));
        productRequire.setUserId(userInfo.get(0).getId().toString());
        productRequire = invoke("stock.productRequire.create", productRequire); //新增
        productRequire.setUserId(userInfo.get(0).getId().toString());
        invoke("stock.productRequire.approve", productRequire); //审批
        return productRequire;
    }

    /**
     * 获取资金收入类型
     * @return
     */
    public List queryAmtReceipts(){
        return amtReceiptRepository.findAll(JpaDsl.toCriteriaIgnoreNull("valid","EQ",1));
    }
}
